import { Inject, Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class RoleService {

  @Inject()
  private readonly prismaService: PrismaService;

  //创建角色
  async create(createRoleDto: CreateRoleDto) {
    const { name } = createRoleDto;
    const role = await this.prismaService.role.create({
      data: {
        name,
      },
    })
    return {
      message: '创建成功',
    };
  }

  // 查询所有角色
  async findAll() {
    const roles = await this.prismaService.role.findMany();
    return roles;
  }

  // 分配角色
  async assignRole(userId: string, roleId: string) {
    // 判断用户是否有角色了
    const userRoleExist = await this.prismaService.userRole.findFirst({
      where: {
        userId,
      },
    })
    if (userRoleExist) {
      return {
        message: '用户已有角色',
      }
    }
    await this.prismaService.userRole.create({
      data: {
        userId,
        roleId,
      },
    })
    return {
      message: '分配成功',
    };
  }

  // 修改用户角色
  async update(id: string, updateRoleDto: UpdateRoleDto) {
    const { name } = updateRoleDto;
    await this.prismaService.role.update({
      where: {
        id,
      },
      data: {
        name,
      },
    })
    return {
      message: '修改成功',
    };
  }

  // 查看某个角色下的用户
  async findUserByRole(roleId: string) {
    const userRole = await this.prismaService.userRole.findMany({
      where: {
        roleId,
      },
    })
    const userIds = userRole.map((item) => item.userId);
    const users = await this.prismaService.user.findMany({
      where: {
        id: {
          in: userIds,
        },
      },
    })
    return users;
  }

  // 查看某个角色下的权限
  async findAuthorityByRole(roleId: string) {
    const roleAuthority = await this.prismaService.roleAuthority.findMany({
      where: {
        roleId,
      },
    })
    const authorityIds = roleAuthority.map((item) => item.authorityId);
    const authority = await this.prismaService.authority.findMany({
      where: {
        id: {
          in: authorityIds,
        },
      },
    })
    return authority;
  }
}
